package ru.ipo.dces.problemsviewer;

import javax.swing.*;
import java.awt.*;

/**
 * Created by IntelliJ IDEA.
 * User: ilya
 * Date: 09.06.11
 * Time: 16:52
 */
public class ErrorComponent extends JPanel {

    public ErrorComponent(Throwable e) {
        //output to stack trace
        e.printStackTrace();

        setLayout(new BorderLayout(10, 20));

        JLabel title = new JLabel("При открытии задачи произошла ошибка");
        add(title, BorderLayout.NORTH);

        JTextPane exceptionDescription = new JTextPane();
        add(new JScrollPane(exceptionDescription), BorderLayout.CENTER);

        Color bg = UIManager.getColor("Panel.background");
        if (bg != null)
            exceptionDescription.setBackground(bg);

        StringBuilder sb = new StringBuilder();

        sb
                .append("<h2>")
                .append(e.getClass().getCanonicalName())
                .append(": <font color='blue'>")
                .append(e.getMessage())
                .append("</font></h2>");

        appendStackTrace(sb, e);
        e = e.getCause();
        while (e != null) {
            sb.append("<p>Caused by</p>");
            appendStackTrace(sb, e);
        }

        setHtmlToTextPane(exceptionDescription, sb.toString());
    }

    private void appendStackTrace(StringBuilder sb, Throwable e) {
        sb.append("<p>");
        for (StackTraceElement traceElement : e.getStackTrace()) {
            //append stack trace element
            sb
                    .append("&nbsp;&nbsp;&nbsp;&nbsp;<font color='#888888'>at</font> ")
                    .append(traceElement.getClassName())
                    .append(".")
                    .append(traceElement.getMethodName())
                    .append("(<i><u><font color='blue'>")
                    .append(traceElement.getFileName())
                    .append(":")
                    .append(traceElement.getLineNumber())
                    .append("</font></u></i>)")
                    .append("<br>");
        }
        sb.append("</p>");
    }

    private void setHtmlToTextPane(JTextPane pane, String html) {
        pane.setContentType("text/html");
        pane.setText(html);
    }

}
